package com.skydroid.h16

import android.content.Context
import android.content.Intent
import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.skydroid.h16.utils.String2ByteArrayUtils
import com.skydroid.h16.R
import java.io.IOException
import java.nio.ByteBuffer
import kotlin.experimental.xor

class RCDataActivity: AppCompatActivity() {
    protected var PACKAGE_HEADER_BUF = "fengyingdianzi:".toByteArray()

    private var localSocket: LocalSocket? = null

    private var mReadBuffer = ByteBuffer.allocate(4096)

    private var mReadThread : ReadThread? = null

    @Volatile
    var isConnect:Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_rc_data)
        initView()
    }

    companion object{
        fun start(context: Context){
            context.startActivity(
                Intent(context,
                    RCDataActivity::class.java)
            )
        }
    }

    private fun initView(){
        findViewById<View>(R.id.btn_open).setOnClickListener {
            openConnect()
        }
        findViewById<View>(R.id.btn_close).setOnClickListener {
            closeConnect()
        }
        findViewById<View>(R.id.btn_send).setOnClickListener {
            sendData()
        }
    }

    /**
     * 打开连接
     */
    private fun openConnect(){
        Thread{
            localSocket = LocalSocket(LocalSocket.SOCKET_DGRAM)
            localSocket?.bind(LocalSocketAddress("uart3app"))
            localSocket?.connect(LocalSocketAddress("uart3endpoint"))

            isConnect = true

            mReadThread = ReadThread()
            mReadThread?.start()
        }.start()
    }

    /**
     * 关闭连接
     */
    private fun closeConnect(){
        isConnect = false
        //关闭读取线程
        mReadThread?.interrupt()
        mReadThread = null

        //关闭连接
        try {
            localSocket?.shutdownInput()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.shutdownOutput()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.inputStream?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.outputStream?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        localSocket = null

    }

    /**
     * 发送数据
     */
    private fun sendData(){
        Thread{
            var cmd = ByteArray(PACKAGE_HEADER_BUF.size +  8)
            var count = PACKAGE_HEADER_BUF.size
            //写入帧头
            System.arraycopy(PACKAGE_HEADER_BUF,0,cmd,0,count)
            cmd[count++] = 0xB4.toByte()
            cmd[count++] = 2.toByte()
            cmd[count++] = 'R'.toByte()
            cmd[count++] = 1.toByte()
            //写入BCC SUM
            cmd[count] = getBCC(cmd)

            localSocket?.outputStream?.write(cmd)
        }.start()
    }

    /**
     * 数据读取线程
     */
    inner class ReadThread:Thread(){
        override fun run() {
            try {
                var size = 0
                while (isConnect && !isInterrupted ){
                    if(localSocket?.inputStream == null){
                        return
                    }
                    if (localSocket?.inputStream?.available() == 0) {
                        continue
                    }
                    size = localSocket!!.inputStream!!.read(mReadBuffer.array())
                    if (size > 0) {
                        var tempArray = ByteArray(size)
                        mReadBuffer[tempArray, 0, size]
                        Log.e("ReadThread","receive：${String2ByteArrayUtils.bytes2Hex(tempArray)}")
                    }
                    mReadBuffer.clear()
                }
            }catch (e:InterruptedException){
                e.printStackTrace()
            }catch (e: IOException){
                e.printStackTrace()
            }

        }
    }

    fun getBCC(data: ByteArray): Byte {
        var temp = data[0]
        for (i in 1 until data.size - 1) {
            temp = temp xor data[i]
        }
        return temp
    }

    override fun onDestroy() {
        super.onDestroy()
        closeConnect()
    }

}